package hu.gar.web.user;

import java.lang.reflect.Method;
import java.text.Collator;
import java.util.Comparator;
import java.util.Locale;

import org.primefaces.model.SortOrder;

public class LazyUserSorter implements Comparator<UserDisplayVO> {

	private String sortField;

	private SortOrder sortOrder;

	public LazyUserSorter(String sortField, SortOrder sortOrder) {
		this.sortField = sortField;
		this.sortOrder = sortOrder;
	}

	public int compare(UserDisplayVO userVO1, UserDisplayVO userVO2) {
		try {
			String field = this.sortField;
			field = field.substring(0, 1).toUpperCase() + field.substring(1);
			Method method = UserDisplayVO.class.getMethod("get" + field, null);

			Object value1 = method.invoke(userVO1);
			Object value2 = method.invoke(userVO2);

			// int value = ((Comparable) value1).compareTo(value2);
			Collator collator = Collator.getInstance(new Locale("hu", "HU"));
			int value = collator.compare(value1.toString().toLowerCase(),
					value2.toString().toLowerCase());

			return SortOrder.ASCENDING.equals(sortOrder) ? value : -1 * value;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}